import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

//使用懒加载的方式引入组件
const User = () => import(/* webpackChunkName: "user" */ '../views/User.vue')
const Info = () => import(/* webpackChunkName: "user" */ '../views/Info.vue')
const Login = () => import(/* webpackChunkName: "user" */ '../views/Login.vue')
Vue.use(VueRouter)

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  },
  {
    path:'/user/:id',
    name:'User',
    component:User
  },
  {
    path:'/info',
    name:'Info',
    component:Info
  },
  {
    path:'/login',
    name:'Login',
    component:Login
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})


//全局前置钩子 进入前做的事情
//to:要去的路由
//from:来的路由
//next:放行
router.beforeEach((to, from, next) => {
    console.log('前置to:',to);
    console.log('前置from:',from);
    console.log('前置next:',next);
    //验证是否登录
    if(to.name !== 'Login'){
        if(window.uname && window.upass){
            next();
        }else{
            alert("请先登录")
            next('/login');
        }
    }
    next();//必须调用  才能放行

})
/* 
  全局的后置
      to:要去跳转路由
      form:来的路由
*/
router.afterEach( (to,from) => {
    console.log('欢迎',window.uname);
})

export default router
